﻿using System;
using System.Diagnostics;
using log4net;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using SnapUtilities;

namespace LuceneIndexer
{
    public class Indexer
    {
        private static readonly ILog Logger =
            LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private readonly Stopwatch stopwatch = new Stopwatch();
        private readonly Directory directory;

        public Indexer(Directory directory)
        {
            this.directory = directory;
        }

        public void IndexNewsItems(DateTime splitDate)
        {
            var analyzer = new StandardAnalyzer( Lucene.Net.Util.Version.LUCENE_29 );
            var writer = new IndexWriter( directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED );

            var newsInfos = Utilities.PullNewsInfo( DateTime.MinValue, splitDate );
            stopwatch.Restart();
            foreach (var newsId in newsInfos.Keys)
            {
                var document = new Document();
                document.Add( new Field( "id", newsId.ToString(),
                                         Field.Store.YES,
                                         Field.Index.NOT_ANALYZED ) );
                document.Add( new Field( "body", newsInfos[newsId],
                                         Field.Store.NO,
                                         Field.Index.ANALYZED ) );
                writer.AddDocument( document );
            }
            writer.Close();
            stopwatch.Stop();
            Logger.DebugFormat( "Indexed {0} documents in {1}", newsInfos.Keys.Count, stopwatch.Elapsed );
        }
        
        
    }
}
